package com.andrewchatham.pony;

import java.util.List;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;

public class Preferences extends PreferenceActivity {
  public static String KEY = "com.andrewchatham.SynctasticPony";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    addWifiOptions();
  }

  /**
   * Normalize the SSID. The API claims to put quotes around it when it's a string, but that's not always true. Always strip surrounding quotes. 
   * 
   * @param ssid
   */
  public static String normalizeSSID(String ssid) {
    if (ssid == null) return null;
    return ssid.replace("\"", "");
  }

  /**
   * Populate the ssid preference list with all known wifi configurations. 
   */
  private void addWifiOptions() {
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
    CharSequence [] ssids = new CharSequence[configs.size()];
    for (int k = 0; k < configs.size(); ++k) {
      ssids[k] = normalizeSSID(configs.get(k).SSID);
    }

    ListPreference ssid = (ListPreference) findPreference(getString(R.string.ssid_key));
    ssid.setDefaultValue(wifi.getConnectionInfo().getSSID());
    ssid.setEntries(ssids);
    ssid.setEntryValues(ssids);
  }
}
